<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-2/5 xl:w-1/5 tree">
      <div class="m-4 mr-0 overflow-hidden bg-white tree-content">
        <!-- <BasicForm> -->
        <BasicTitle>检查规范目录</BasicTitle>
        <div class="enterprise">
          <label for="">企业类别：</label>
          <Select
            v-model:value="enterpriseType"
            :options="enterpriseOptions"
            @change="enterpriseOptionsChange"
            placeholder="请选择企业类别"
          >
          </Select>
        </div>
        <div style="padding: 5px">
          <a-button @click="addCatalogue" type="primary" class="mr-2"> 新增 </a-button>
          <a-button @click="editCatalogue" type="primary" class="mr-2"> 编辑 </a-button>
          <a-button @click="delCatalogue" type="primary" class="mr-2"> 删除 </a-button>
        </div>
        <BasicTree
          title=""
          :clickRowToExpand="false"
          :treeData="treeData"
          :replaceFields="{ key: 'id', title: 'name' }"
          @select="handleSelect"
        />
      </div>
    </div>
    <BasicTable @register="registerTable" class="w-3/5 xl:w-4/5">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">新增</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑用户资料',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除此账号',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <Zmodal @register="treeModal" @success="treeSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, onMounted, ref } from 'vue';
  import { Select } from 'ant-design-vue';
  import { BasicTree } from '/@/components/Tree';
  //import { getDeptList } from '/@/api/demo/system';
  import { BasicTitle } from '/@/components/Basic';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  //import { getAccountList } from '/@/api/demo/system';
  import { PageWrapper } from '/@/components/Page';
  import Zmodal from './ZtreeModel.vue';
  import { useModal } from '/@/components/Modal';
  import AccountModal from './AccountModal.vue';

  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '/@/hooks/web/usePage';

  import {
    getRuleList,
    industryLIstanbul,
    treeList,
    addRuleCatalog,
    updateRule,
    addRule,
    updateRuleCatalog,
    delRule,
    delRuleCatalog,
  } from '/@/api/busi/rule';

  export default defineComponent({
    name: 'RuleManager',
    components: {
      BasicTable,
      PageWrapper,
      AccountModal,
      TableAction,
      BasicTree,
      BasicTitle,
      Zmodal,
      Select,
    },
    setup() {
      const go = useGo();
      const [registerModal, { openModal }] = useModal();
      const searchInfo = reactive<Recordable>({});
      const treeData = ref<TreeItem[]>([]);
      const enterpriseType = ref(''); //企业类别
      const enterpriseTypeValue = ref('');
      const enterpriseOptions = ref([]); //企业数据
      const [treeModal, { openModal: openZtreeModal }] = useModal();
      const { createMessage } = useMessage();
      async function fetch() {
        //树接口
        const treeDataList = await treeList({ industryId: enterpriseType.value });
        console.log(treeDataList);
        treeData.value = [treeDataList.returnData || {}];
      }

      //企业change
      function enterpriseOptionsChange(value: Value) {
        enterpriseType.value = value;
        fetch();
      }

      let treeKey = {
        id: '-1',
      };

      function handleSelect(keys) {
        console.log(keys);
        searchInfo.deptId = keys[0];
        reload();
        treeKey.id = keys;
      }

      onMounted(() => {
        //获取企业数据
        enterprise();
      });

      async function enterprise() {
        //企业数据接口
        const Options = await industryLIstanbul();
        var OptionsValue = [];
        for (var m = 0; m < Options.returnData.list.length; m++) {
          var obj = {};
          obj.label = Options.returnData.list[m].name;
          obj.value = Options.returnData.list[m].id;
          OptionsValue.push(obj);
        }
        enterpriseOptions.value = OptionsValue;
        enterpriseType.value = OptionsValue[0].value;
        fetch();
      }

      const [registerTable, { reload }] = useTable({
        title: '检查规范列表',
        api: getRuleList,
        searchInfo: { industryId: enterpriseType.value || '' },
        rowKey: 'id',
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: false,
        bordered: true,
        beforeFetch: (h) => {
          //表格参数
          /*          h = treeKey;
          console.log(h); */
          return h;
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        console.log(record);
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      // 新增目录
      function addCatalogue() {
        if (treeKey.id) {
          openZtreeModal(true, {
            treeKey,
            isUpdate: false,
          });
        } else {
          createMessage.error('请选择一个父节点！');
        }
      }

      // 编辑目录
      function editCatalogue() {
        if (treeKey.id) {
          if (treeKey.id == '-1') {
            createMessage.error('根目录不能编辑！');
          } else {
            openZtreeModal(true, {
              treeKey,
              isUpdate: true,
            });
          }
        } else {
          createMessage.error('请选择一个要编辑的目录！');
        }
      }

      //输节点新增编辑
      function treeSuccess({ isUpdate, values }) {
        console.log(isUpdate, values);
        if (isUpdate) {
          // 编辑接口 编辑节点i（treeKey.id）
          updateRuleCatalog({
            name: values.name,
            id: treeKey.id[0],
          });
          createMessage.success('编辑成功');
        } else {
          //新增接口
          addRuleCatalog({
            name: values.name,
            parentId: treeKey.id == '-1' ? '0' : treeKey.id[0],
            industryId: enterpriseType.value,
          });
          createMessage.success('新增成功');
        }
        fetch();
      }

      // 删除目录
      async function delCatalogue() {
        if (treeKey.id == '-1') {
          createMessage.error('根目录不能删除！');
        } else {
          await delRuleCatalog({ id: treeKey.id[0] });
          await fetch();
        }
      }

      function handleDelete(record: Recordable) {
        console.log(record);
        //删除表格数据接口
        delRule({ id: record.id });
        reload();
      }

      //新增编辑表格
      function handleSuccess({ isUpdate, values }) {
        console.log(isUpdate, values);
        if (isUpdate) {
          //编辑表格接口
          updateRule({
            checkBasis: values.checkBasis,
            checkContent: values.checkContent,
            checkMethod: values.checkMethod,
            projectName: values.projectName,
            id: values.id,
          });
        } else {
          //新增表格接口
          addRule({
            parentId: treeKey.id[0],
            checkBasis: values.checkBasis,
            checkContent: values.checkContent,
            checkMethod: values.checkMethod,
            projectName: values.projectName,
          });
        }
        reload();
      }

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        searchInfo,
        treeData,
        addCatalogue,
        editCatalogue,
        delCatalogue,
        treeModal,
        enterpriseType,
        enterpriseOptions,
        treeSuccess,
        enterpriseOptionsChange,
        enterpriseTypeValue,
      };
    },
  });
</script>
<style scoped>
  .enterprise {
    padding: 10px 10px 0 10px;
    width: 100%;
    display: flex;
    align-items: center;
  }

  ::v-deep(.enterprise .ant-select) {
    width: calc(100% - 80px);
  }

  .tree {
    height: calc(100% - 16px);
    padding: 0 0 16px 0;
  }

  .tree-content {
    background: #fff;
    padding: 5px;
    height: 100%;
  }
</style>
